package com.jsmile.cloud.authc.sys;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDictPageQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDictQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDictUpdate;
import com.jsmile.cloud.authc.api.res.ResSysDict;
import com.jsmile.cloud.authc.sys.model.SysDictionary;
import com.jsmile.cloud.authc.sys.repo.SysDictionaryRepository;
import com.jsmile.cloud.authc.sys.repo.SysDictionarySearchRepository;
import com.jsmile.mall.api.exception.ExceptionKit;
import com.jsmile.mall.api.kit.StrKit;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class SysDictApplicationService {

    private final SysDictionarySearchRepository sysDictionarySearchRepository;
    private final SysDictionaryRepository sysDictionaryRepository;

    public IPage<ResSysDict> getPageList(ReqSysDictPageQuery reqSysDictPageQuery) {
        ExceptionKit.checkNotNull(reqSysDictPageQuery.getCurTenantId(), "租户id不能为空!");
        log.info("字典查询:{]", reqSysDictPageQuery);
        return sysDictionarySearchRepository.pageQuery(reqSysDictPageQuery).convert(x -> BeanUtil.toBean(x, ResSysDict.class));
    }

    public List<ResSysDict> getList(ReqSysDictQuery reqSysDictQuery) {
        ExceptionKit.checkNotNull(reqSysDictQuery.getCurTenantId(), "租户id不能为空!");
        log.info("字典查询:{]", reqSysDictQuery);
        return sysDictionarySearchRepository.getList(reqSysDictQuery).stream().map(x -> BeanUtil.toBean(x, ResSysDict.class)).collect(Collectors.toList());
    }

    public List<ResSysDict> findDictByCode(ReqSysDictQuery reqSysDictQuery) {
        ExceptionKit.checkNotNull(reqSysDictQuery.getCurTenantId(), "租户id不能为空!");
        ExceptionKit.checkArgument(StrKit.isBlank(reqSysDictQuery.getDictCode()), "字典编码不能为空!");
        log.info("字典查询:{]", reqSysDictQuery);
        return sysDictionarySearchRepository.findDictByCode(reqSysDictQuery).stream().map(x -> BeanUtil.toBean(x, ResSysDict.class)).collect(Collectors.toList());
    }

    public boolean saveDict(ReqSysDictUpdate reqSysDictUpdate) {
        return sysDictionaryRepository.save(SysDictionary.create(reqSysDictUpdate));
    }

    public boolean updateDict(ReqSysDictUpdate reqSysDictUpdate) {
        return sysDictionaryRepository.updateById(SysDictionary.create(reqSysDictUpdate));
    }

    public boolean deleteDict(ReqSysDictUpdate reqSysDictUpdate) {
        return sysDictionaryRepository.removeById(reqSysDictUpdate.getId());
    }
}
